package org.springframework.ai.dashscope.autoconfigure;

import io.micrometer.observation.ObservationRegistry;
import org.springframework.ai.chat.observation.ChatModelObservationConvention;
import org.springframework.ai.embedding.observation.EmbeddingModelObservationConvention;
import org.springframework.ai.model.tool.DefaultToolCallingManager;
import org.springframework.ai.model.tool.autoconfigure.ToolCallingAutoConfiguration;
import org.springframework.ai.retry.autoconfigure.SpringAiRetryAutoConfiguration;
import org.springframework.ai.dashscope.DashscopeAiChatModel;
import org.springframework.ai.dashscope.DashscopeAiEmbeddingModel;
import org.springframework.ai.dashscope.DashscopeAiImageModel;
import org.springframework.ai.dashscope.api.DashscopeAiApi;
import org.springframework.ai.dashscope.api.DashscopeAiImageApi;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration;
import org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestClient;
import org.springframework.web.reactive.function.client.WebClient;

/**
 * {@link AutoConfiguration Auto-configuration} for Dashscope.
 *
 * @author wangjun
 */
@AutoConfiguration(after = { RestClientAutoConfiguration.class, WebClientAutoConfiguration.class, SpringAiRetryAutoConfiguration.class, ToolCallingAutoConfiguration.class })
@ConditionalOnClass(DashscopeAiApi.class)
@EnableConfigurationProperties({ DashscopeAiConnectionProperties.class, DashscopeAiChatProperties.class,
		DashscopeAiEmbeddingProperties.class, DashscopeAiImageProperties.class })
@ImportAutoConfiguration(classes = { SpringAiRetryAutoConfiguration.class, RestClientAutoConfiguration.class,
		WebClientAutoConfiguration.class, ToolCallingAutoConfiguration.class })
public class DashscopeAiAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnProperty(prefix = DashscopeAiChatProperties.CONFIG_PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
	public DashscopeAiChatModel dashscopeChatModel(DashscopeAiConnectionProperties commonProperties,
												DashscopeAiChatProperties chatProperties, ObjectProvider<RestClient.Builder> restClientBuilderProvider,
												ObjectProvider<WebClient.Builder> webClientBuilderProvider,
												RetryTemplate retryTemplate, ResponseErrorHandler responseErrorHandler,
												ObjectProvider<ObservationRegistry> observationRegistry,
												ObjectProvider<ChatModelObservationConvention> observationConvention) {

		var dashscopeAiApi = dashscopeAiApi(chatProperties.getBaseUrl(), commonProperties.getBaseUrl(),
				chatProperties.getApiKey(), commonProperties.getApiKey(),
				restClientBuilderProvider.getIfAvailable(RestClient::builder), webClientBuilderProvider.getIfAvailable(WebClient::builder), responseErrorHandler);

		var chatModel = new DashscopeAiChatModel(dashscopeAiApi, chatProperties.getOptions(),
				DefaultToolCallingManager.builder().build(), retryTemplate, observationRegistry.getIfUnique(() -> ObservationRegistry.NOOP));

		observationConvention.ifAvailable(chatModel::setObservationConvention);

		return chatModel;
	}

	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnProperty(prefix = DashscopeAiEmbeddingProperties.CONFIG_PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
	public DashscopeAiEmbeddingModel dashscopeAiEmbeddingModel(DashscopeAiConnectionProperties commonProperties,
															DashscopeAiEmbeddingProperties embeddingProperties, ObjectProvider<RestClient.Builder> restClientBuilderProvider, ObjectProvider<WebClient.Builder> webClientBuilderProvider,
															RetryTemplate retryTemplate, ResponseErrorHandler responseErrorHandler,
															ObjectProvider<ObservationRegistry> observationRegistry,
															ObjectProvider<EmbeddingModelObservationConvention> observationConvention) {

		var dashscopeAiApi = dashscopeAiApi(embeddingProperties.getBaseUrl(), commonProperties.getBaseUrl(),
				embeddingProperties.getApiKey(), commonProperties.getApiKey(), restClientBuilderProvider.getIfAvailable(RestClient::builder), webClientBuilderProvider.getIfAvailable(WebClient::builder), responseErrorHandler);

		var embeddingModel = new DashscopeAiEmbeddingModel(dashscopeAiApi, embeddingProperties.getMetadataMode(),
				embeddingProperties.getOptions(), retryTemplate,
				observationRegistry.getIfUnique(() -> ObservationRegistry.NOOP));

		observationConvention.ifAvailable(embeddingModel::setObservationConvention);

		return embeddingModel;
	}

	private DashscopeAiApi dashscopeAiApi(String baseUrl, String commonBaseUrl, String apiKey, String commonApiKey,
									   RestClient.Builder restClientBuilder, WebClient.Builder webClientBuilder,
									   ResponseErrorHandler responseErrorHandler) {

		String resolvedBaseUrl = StringUtils.hasText(baseUrl) ? baseUrl : commonBaseUrl;
		Assert.hasText(resolvedBaseUrl, "DashscopeAI base URL must be set");

		String resolvedApiKey = StringUtils.hasText(apiKey) ? apiKey : commonApiKey;
		Assert.hasText(resolvedApiKey, "DashscopeAI API key must be set");

		return new DashscopeAiApi(resolvedBaseUrl, resolvedApiKey, restClientBuilder, webClientBuilder, responseErrorHandler);
	}

	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnProperty(prefix = DashscopeAiImageProperties.CONFIG_PREFIX, name = "enabled", havingValue = "true",
			matchIfMissing = true)
	public DashscopeAiImageModel dashscopeAiImageModel(DashscopeAiConnectionProperties commonProperties,
													DashscopeAiImageProperties imageProperties, ObjectProvider<RestClient.Builder> restClientBuilderProvider, RetryTemplate retryTemplate,
													ResponseErrorHandler responseErrorHandler) {

		String apiKey = StringUtils.hasText(imageProperties.getApiKey()) ? imageProperties.getApiKey()
				: commonProperties.getApiKey();

		String baseUrl = StringUtils.hasText(imageProperties.getBaseUrl()) ? imageProperties.getBaseUrl()
				: commonProperties.getBaseUrl();

		Assert.hasText(apiKey, "DashscopeAI API key must be set");
		Assert.hasText(baseUrl, "DashscopeAI base URL must be set");

		var zhiPuAiImageApi = new DashscopeAiImageApi(baseUrl, apiKey, restClientBuilderProvider.getIfAvailable(RestClient::builder), responseErrorHandler);

		return new DashscopeAiImageModel(zhiPuAiImageApi, imageProperties.getOptions(), retryTemplate);
	}

}
